﻿using System;
using System.Collections.Generic;
using System.Text;

namespace hedefgrup.reports.common
{
    public class TreeXPathParser
    {
        public List<TreeXPathSegment> Segments = new List<TreeXPathSegment>();

        public TreeXPathParser(string xPath)
        {
            string currentToken = null;
            int valueReadState = 0;
            TreeXPathSegment currentSegment = new TreeXPathSegment();

            for (int i = 0; i < xPath.Length; i++)
            {
                switch (xPath[i])
                {
                    case '/':
                        if (!string.IsNullOrEmpty(currentToken))
                        {
                            currentSegment.Key = currentToken;
                            currentToken = string.Empty;
                        }
                        Segments.Add(currentSegment);
                        currentSegment = new TreeXPathSegment();
                        currentToken = string.Empty;
                        break;

                    case '(':
                    case '[':
                        currentSegment.Key = currentToken;
                        currentToken = string.Empty;
                        break;

                    case ')':
                        currentSegment.Type = currentToken;
                        currentToken = string.Empty;
                        break;

                    case '@':
                        break;

                    case '=':
                        currentSegment.Attribute = currentToken;
                        currentToken = string.Empty;
                        break;

                    case '\'':
                        if (valueReadState == 0)
                        {
                            valueReadState = 1;
                        }
                        else
                        {
                            currentSegment.AttributeValue = currentToken;
                            currentToken = string.Empty;
                            valueReadState = 0;
                        }
                        break;

                    case ']':
                        break;

                    default:
                        currentToken += xPath[i];
                        break;
                }
            }
            if (!string.IsNullOrEmpty(currentToken))
            {
                currentSegment.Key = currentToken;
                currentToken = string.Empty;
            }
            Segments.Add(currentSegment);
        }
    }
}
